import { Component, OnInit } from '@angular/core';
import { AdminService, ProblemDTO } from '../../services/admin.service';
import { Router } from '@angular/router';

@Component({
  standalone: false,
  selector: 'app-admin-dashboard',
  templateUrl: './admin-dashboard.component.html',
  styleUrls: ['./admin-dashboard.component.css']
})
export class AdminDashboardComponent implements OnInit {
  problems: ProblemDTO[] = [];
  loading = false;
  error: string | null = null;

  constructor(
    private adminService: AdminService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.loadProblems();
  }

  loadProblems(): void {
    this.loading = true;
    this.error = null;
    
    this.adminService.getAllProblems().subscribe({
      next: (response) => {
        if (response.success && response.data) {
          this.problems = response.data;
        } else {
          this.error = response.message || '获取题目列表失败';
        }
        this.loading = false;
      },
      error: (error) => {
        this.error = '网络错误，请稍后重试';
        this.loading = false;
        console.error('Error loading problems:', error);
      }
    });
  }

  createProblem(): void {
    this.router.navigate(['/admin/problems/create']);
  }

  editProblem(id: number): void {
    this.router.navigate(['/admin/problems/edit', id]);
  }

  batchImport(): void {
    this.router.navigate(['/admin/problems/batch-import']);
  }

  deleteProblem(id: number): void {
    if (confirm('确定要删除这道题目吗？此操作不可撤销。')) {
      this.adminService.deleteProblem(id).subscribe({
        next: (response) => {
          if (response.success) {
            this.problems = this.problems.filter(p => p.id !== id);
          } else {
            alert('删除失败：' + response.message);
          }
        },
        error: (error) => {
          alert('删除失败，请稍后重试');
          console.error('Error deleting problem:', error);
        }
      });
    }
  }

  getDifficultyClass(difficulty: string): string {
    switch (difficulty.toLowerCase()) {
      case 'easy': return 'difficulty-easy';
      case 'medium': return 'difficulty-medium';
      case 'hard': return 'difficulty-hard';
      default: return '';
    }
  }
} 